import React from "react";
const Reserve = () => {
    const back = () => {
        React.navigate(-1)
    }
    React.useEffect(() => {
        getRoomData()
        getCouponData()
        getHouseHold()
    }, [])
    // 接收酒店id
    const [useSearchParams] = React.Router.useSearchParams()
    const [rid, setRid] = React.useState(useSearchParams.get("rid"))

    // 获取房间数据
    const [room, setRoom] = React.useState({
        name: "",
        thumb_text: "",
        flag_text: [],
        content: "",
        price: 0,
        total: 0,
        state: false,
        surplus: 0
    })
    const getRoomData = async () => {
        let result = await React.HTTP.post("/room/info", { rid })
        if (result.code == 1) {
            setRoom(result.data)
        } else {
            React.error(result.msg, () => {
                React.navigate(-1)
            })
            return false
        }
    }

    // 获得优惠券数据
    const busid = React.Business.id ?? 0;
    const [coupon, setCoupon] = React.useState([])
    const [couponPicker, setCouponPicker] = React.useState([])
    const getCouponData = async () => {
        let result = await React.HTTP.post("/room/coupon", { busid })
        if (result.code == 1) {
            const couponList: any = [[]]
            result.data.map((item: any) => {
                couponList[0].push({
                    label: item.coupon.title + " " + item.coupon.rate * 10 + "折",
                    value: item.id
                })
            })
            setCoupon(result.data)
            setCouponPicker(couponList)
        }
    }

    // 获取住客信息
    const [houseHold, setHouseHold] = React.useState([])
    const getHouseHold = async () => {
        let result = await React.HTTP.post("/room/household", { busid })
        if (result.code == 1) {
            setHouseHold(result.data)
        } else {
            React.error(result.msg)
        }
    }

    // 渲染数据
    // 展示标识
    const [showCalendar, setShowCalendar] = React.useState(false)
    const [showCoupon, setShowCoupon] = React.useState(false)
    const [showHousehold, setShowHousehold] = React.useState(false)
    // 展示的文本数据
    const [dateStr, setDataStr] = React.useState("");
    const [couponStr, setCouponStr] = React.useState("");
    const [houseHoldStr, setHouseHoldStr] = React.useState("");
    const [day, setDay] = React.useState(0);
    // 请求需要的数据
    const [data, setData] = React.useState({
        busid,
        rid,
        guest: "",
        originPrice: 0,
        price: 0,
        starttime: '',
        endtime: '',
        couponid: "0",
        remark: "",
        paytype:""
    })

    // 选择日期
    const selectCalendar = (val: any) => {
        // var datestr = `2024-03-20 - 2024-03-25`
        var datestr = `${new Date(val[0]).toLocaleDateString()} - ${new Date(val[1]).toLocaleDateString()}`
        setDataStr(datestr)
        const needData: any = {
            starttime: Date.parse(new Date(val[0]).toLocaleDateString()) / 1000,
            endtime: Date.parse(new Date(val[1]).toLocaleDateString()) / 1000
        }
        // 如果只选择了一个日期，默认结束日期为开始时间的第二天
        if(needData.endtime == needData.starttime){
            needData.endtime += 86400
        }
        // 获得总天数
        setDay((needData.endtime - needData.starttime) / 86400 > 0 ? (needData.endtime - needData.starttime) / 86400 : 1);
        const originPrice = (needData.endtime - needData.starttime) / 86400 * room.price > 0 ? (needData.endtime - needData.starttime) / 86400 * room.price : Number(room.price)
        const price = rate * originPrice
        setData({ ...data, ...needData, originPrice, price })
    }

    // 选择住户
    const selectHousehold = (val: any, label: any) => {
        // 获得住户名字
        const householdName: any = []
        // 获取住户id
        const guest = val.join(",")
        houseHold.map((item: any) => {
            if (val.includes(item.id)) {
                householdName.push(item.nickname)
            }
        })
        setHouseHoldStr(householdName.join("、"))
        setData({ ...data, guest })
    }

    // 选择优惠券
    // 折扣
    let [rate, setRate] = React.useState(1)
    const selectCoupon = (val: any) => {
        // 获得优惠券名称
        let couponName = ""
        coupon.map((item: any) => {
            if (val.includes(item.id)) {
                couponName = item.coupon.title
                // 优惠券记录id
                const couponid = item.id
                // 优惠券折扣
                rate = item.coupon.rate
                const price = rate * data.originPrice
                setRate(rate)
                setCouponStr(couponName)
                setData({ ...data, couponid, price })
                return false
            }
        })
    }

    // 取消使用优惠券
    const cancelCoupon = () => {
        const couponid = ""
        const price = data.originPrice
        setCouponStr("")
        setData({ ...data, couponid, price })
    }

    // 选择支付方式
    const [showPayType, setShowPayType] = React.useState(false)
    const [payTypePicker, setPayTypePicker] = React.useState([[
        { label: "余额支付", value: "0" },
        { label: "微信支付", value: "1" },
        { label: "支付宝支付", value: "2" },
    ]])
    const [payTypeStr, setPayTypeStr] = React.useState("")
    const selectPayType = (val: string) => {
        switch (val[0]) {
            case "0":
                setPayTypeStr("余额支付")
                setData({...data,paytype:val[0]})
                break;
            case "1":
                setPayTypeStr("微信支付")
                setData({...data,paytype:val[0]})
                break;
            case "2":
                setPayTypeStr("支付宝支付")
                setData({...data,paytype:val[0]})
                break;
        }
    }
    // 提交订单
    const confirm = async () => {
        // 判断是否填写时间
        if(!data.starttime || !data.endtime){
            React.error("请选择入住时间");
            return false
        }
        if(!data.guest){
            React.error("请选择入住人");
            return false
        }
        if(!data.paytype){
            React.error("请选择支付方式");
            return false
        }
        let result = await React.HTTP.post("/room/order",data)
        if(result.code == 1){
            React.success(result.msg,()=>{
                React.navigate(result.url)
            })
        }else{
            React.error(result.msg)
            return false
        }
    }

    return (<>
        <link rel="stylesheet" href="/assets/css/confirm.css" />
        <React.UI.NavBar
            onBack={back}
            style={{ background: `rgb(55, 68, 134)`, color: '#fff' }}
        >提交订单</React.UI.NavBar>
        <div className="skeleton">
            <div className="detail">
                <div className="thumb">
                    <img src={room.thumb_text} alt="" />
                </div>
                <div className="right">
                    <p>{room.name}</p>
                    <p>￥{room.price} / 晚</p>
                    <div className="tips">
                        {room.flag_text && room.flag_text.map((flag: any, index: any) => <span key={index}> {flag} </span>)}
                    </div>
                </div>
            </div>
            <div className="skeleton_rect">
                <form>
                    <div className="item">
                        <label>入住日期</label>
                        <React.UI.Input type="text" onClick={() => setShowCalendar(true)} onChange={() => { return false }} className="item_right" value={dateStr} placeholder="请选择入住日期" />
                        <React.UI.CalendarPicker
                            visible={showCalendar}
                            min={new Date()}
                            selectionMode='range'
                            onClose={() => setShowCalendar(false)}
                            onMaskClick={() => setShowCalendar(false)}
                            onConfirm={selectCalendar}
                        />
                    </div>
                    <div className="item">
                        <label>住客信息</label>
                        <React.UI.Input type="text" className="item_right" placeholder="请选择住客信息" value={houseHoldStr} onClick={() => setShowHousehold(true)} />
                        <button type="button" className="btn">
                            <React.Router.Link to={'/business/guest'}>添加</React.Router.Link>
                        </button>
                        {/* 弹出层组件 */}
                        <React.UI.Popup
                            visible={showHousehold}
                            onMaskClick={() => setShowHousehold(false)}
                            destroyOnClose
                        >
                            <div
                                style={{ height: '40vh', overflowY: 'scroll', padding: '20px' }}
                            >
                                <React.UI.CheckList
                                    multiple={true}
                                    onChange={selectHousehold}
                                >
                                    {houseHold && houseHold.map((item: any, key: number) =>
                                        <React.UI.CheckList.Item key={key} value={item.id}>
                                            {item.nickname}
                                        </React.UI.CheckList.Item>
                                    )}
                                </React.UI.CheckList>

                                <React.UI.Button color="primary" block style={{ width: '100%' }} onClick={() => setShowHousehold(false)}>确认</React.UI.Button>

                            </div>
                        </React.UI.Popup>
                    </div>
                    {/* 优惠券 */}
                    <div className="item">
                        {coupon.length ?
                            <div className='skeleton_price' style={{ margin: 0, padding: 0 }}>
                                <label>优惠券</label>
                                <React.UI.Input type="text" className="item_right" placeholder="请选择优惠券" value={couponStr} onClick={() => setShowCoupon(true)} />
                                {couponStr ? <button type="button" className="btn" onClick={cancelCoupon}>取消</button> : ""}
                                <React.UI.Picker
                                    columns={couponPicker}
                                    visible={showCoupon}
                                    onClose={() => setShowCoupon(false)}
                                    onConfirm={selectCoupon}
                                    touch-action="auto"
                                >
                                </React.UI.Picker>
                            </div>
                            :
                            ""
                        }
                    </div>
                    <div className="item">
                        <label>支付方式</label>
                        <React.UI.Input type="text" className="item_right" placeholder="请选择支付方式" value={payTypeStr} onClick={() => setShowPayType(true)} />
                        <React.UI.Picker
                            columns={payTypePicker}
                            visible={showPayType}
                            onClose={() => setShowPayType(false)}
                            onConfirm={selectPayType}
                            touch-action="auto"
                        >
                        </React.UI.Picker>
                    </div>
                    {/* remark */}
                    <div className="item">
                        <label>备注</label>
                        <React.UI.TextArea type="text" className="item_right" placeholder="请输入备注" value={data.remark} onChange={(val: string) => setData({ ...data, remark: val })} />
                    </div>
                </form>
            </div>
            <div className="skeleton_price">
                <div className="tips">房间费用</div>
                <div className="prices">
                    <span>￥{data.originPrice}</span>
                    <span>共 {day} 晚</span>
                </div>
            </div>
        </div>
        <div className="comfirm_foot-bar">
            {data.price != data.originPrice ?
                <div className="text">
                    <span>优惠价格:</span>
                    <span>￥{data.price}</span>
                    <s>原价：￥{data.originPrice}</s>
                </div> :
                <div className="text">
                    <span>总价:</span>
                    <span>￥{data.originPrice}</span>
                </div>
            }
            <React.UI.Button onClick={confirm} color='primary' disabled={room.state ? false : true}>提交订单</React.UI.Button>
        </div>
    </>)
}

export default Reserve